/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.widget;

import com.mol.market.R;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

/**
 * 实现了列表功能的Fragment
 * @author Chaos	
 * @Description TODO
 * @date 2012-12-12 
 */
public abstract class AbsListViewFragment extends BaseFragmentWrapper{
    /**
     * View的最顶层
     */
    private View mAncestor = null;
    /**
     * 无论横屏或者竖屏，都要初始化这个AbsListView.
     */
    private AbsListView mAbsListView = null;
    private LinearLayout mTitleView = null;
    /**
     * FooterView
     */
    private View mFooterView = null;
    /**
     * HeaderView
     */
    private View mHeaderView = null;
    /**
     * 包含Header
     */
    private boolean mContainHeader = false;
    /**
     * 包含Footer
     */
    private boolean mContainFooter = false;
    
    @Override
    protected View onCreateViewPort(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        
        mAncestor = initLayout(inflater, container, savedInstanceState);
        mTitleView = (LinearLayout) mAncestor.findViewById(R.id.titleLayout);

        initTitleView(inflater, mTitleView);
        initAbsListView(mAncestor);
        
        View emptyView = initEmptyView(inflater, mAncestor, savedInstanceState);
        mAbsListView.setEmptyView(emptyView);
        
        //添加Header和Footer
        addHeaderAndFooter(inflater, mAbsListView);
        
        ListAdapter adapter = initAdapter();
        if(adapter == null){
            throw new IllegalArgumentException("the listAdapter mustbe not null!");
        }
        
        //初始化AbsListView，如果需要.
        initAbsListView(mAbsListView);
       
        setAdapter(mAbsListView, adapter);
        
        return mAncestor;
    }
    
    /**
     * <strong>What a pity !!!!!</strong>
     * <br>
     * <code>AbsListView.setAdapter</code> <em><b>requires API level 11</b></em>
     */
    protected void setAdapter(AbsListView absListView, ListAdapter adapter) {
        if (absListView instanceof GridView) {
            ((GridView) absListView).setAdapter(adapter);
        } else if (absListView instanceof ListView) {
            ((ListView) absListView).setAdapter(adapter);
        } else{
            throw new RuntimeException("Unable to set Adapter");
        }
    }
    
    public AbsListView getAbsListView(){
        return mAbsListView;
    }
    
    public ListAdapter getAdapter(){
        if(mAbsListView != null){
            return mAbsListView.getAdapter();
        }else{
            return null;
        }
    }
    
    
    /**
     * 当横竖屏切换时，是否保存List.
     */
    protected boolean isCacheListWhenOriChange(){
        return true;
    }
    
//    @Override
//    protected void onOrientationChange(Orientation oldOri, Orientation newOri) {
//        super.onOrientationChange(oldOri, newOri);
//    }
    
    /**
     * 返回View的顶层
     * @param 
     */
    public View getAncestor(){
        return mAncestor;
    }
    
    /**
     * 初始化AbsListView.
     * @param ancestor
     */
    private void initAbsListView(View ancestor){
        if(mAbsListView == null){
            mAbsListView = (AbsListView) ancestor.findViewById(android.R.id.list);
            
            if(mAbsListView == null){
                throw new IllegalStateException("There should be a AbsListView which ID is android.R.id.list");
            }
        }
    }
    
    
    protected void addHeaderAndFooter(LayoutInflater inflater,AbsListView absListView) {
        mFooterView = initFooterView(inflater);
        
        if(mFooterView != null){
            addFooter(getAbsListView(), mFooterView);
            mContainFooter = true;
        }
        
        mHeaderView = initHeaderView(inflater);
        
        if(mHeaderView != null){
            addHeader(getAncestor(), getAbsListView(), mHeaderView);
            mContainHeader = true;
        }
    }
    
    /**
     *  添加页脚，实现下拉加载时显示的页面。 
     */
    private void addFooter(AbsListView view,View footerView){
        if (view instanceof ListView) {
            ((ListView) view).addFooterView(footerView, null, false);
        } else if (view instanceof FooterViewCarriers) {
            ((FooterViewCarriers) view).addFooterView(getAncestor(), footerView);
        } else {
            if (!addFooterView(getAncestor(), view, footerView)) {
                throw new IllegalArgumentException("Don't know how to add FooterView");
            }
        }
        
        //set the footerView gone
        footerView.setVisibility(View.GONE);
    }
    
    /**
     * AbsListView的子类不会添加FooterView，复写此方法，实现添加FooterView.
     * @param 
     * @return 如果已经处理，返回true.
     */
    protected boolean addFooterView(View ancestor,AbsListView view,View footerView){
        return false;
    }
    
    /**
     * AbsListView的子类不会移除FooterView，复写此方法，实现移除FooterView.
     * @param 
     * @return 如果已经处理，返回true.
     */
    protected boolean removeFooterView(View ancestor,AbsListView view,View footerView){
        return false;
    }
    
    public final void removeFooter(View footerView){
        if(getAbsListView() instanceof ListView){
            ((ListView)getAbsListView()).removeFooterView(mFooterView);
            return ;
        }else if(getAbsListView() instanceof FooterViewCarriers){
            ((FooterViewCarriers)getAbsListView()).removeFooterView(getAncestor(),footerView);
        }else{
            if(!removeFooterView(getAncestor(),getAbsListView(), mFooterView)){
                throw new IllegalArgumentException("Don't know how to add FooterView");
            }
        }
    }
    
    private void addHeader(View ancestor,AbsListView view,View headerView){
        if(view instanceof ListView){
            ((ListView)view).addHeaderView(headerView, null, false);
        }else if(view instanceof HeaderViewCarriers){
            ((HeaderViewCarriers)view).addHeaderView(ancestor, headerView);
        }else{
            if(!addHeaderView(getAncestor(),view, headerView)){
                throw new IllegalArgumentException("Don't know how to add HeaderView");
            }
        }
        
        //set the headerView VISIBLE
        headerView.setVisibility(View.VISIBLE);
    }
    
    protected boolean addTitleView(View ancestor,View headerView){
        return true;
    }
    
    /**
     * AbsListView的子类不会添加HeaderView，复写此方法，实现添加HeaderView.
     * @param 
     * @return 如果已经处理，返回true.
     */
    protected boolean addHeaderView(View ancestor,AbsListView view,View headerView){
        return true;
    }
    
    public final void removeHeader(View headerView){
        if(getAbsListView() instanceof ListView){
            ((ListView)getAbsListView()).removeHeaderView(headerView);
            return ;
        }else if(getAbsListView() instanceof HeaderViewCarriers){
            ((HeaderViewCarriers)getAbsListView()).removeHeaderView(getAncestor(), headerView);
        }else{
            if(!removeHeaderView(getAncestor(),getAbsListView(), mFooterView)){
                throw new IllegalArgumentException("Don't know how to remove HeaderView");
            }
        }
    }
    
    /**
     * AbsListView的子类不会添加HeaderView，复写此方法，实现添加HeaderView.
     * @param 
     * @return 如果已经处理，返回true.
     */
    protected boolean removeHeaderView(View ancestor,AbsListView view,View headerView){
        return true;
    }
    
    /**
     * 生成布局<hr>
     * 必须包含一个 <b>id</b> 为 <b>@android:id/list</b> 的<code>AbsListView</code>.
     * @param 
     * @return 
     */
    protected abstract View initLayout(LayoutInflater inflater,ViewGroup container,
            Bundle savedInstanceState);
    
    /**
     * 没有数据时需要展示的View，如果返回空，则不存在EmptyView.
     * @param 
     * @return 
     * @throws
     */
    protected abstract View initEmptyView(LayoutInflater inflater,View ancestor,
            Bundle savedInstanceState);
    
    /**
     * AbsListView需要的Adapter
     * @param 
     * @return 
     * @throws
     */
    protected abstract ListAdapter initAdapter();
    
    /**
     * 初始化AbsListView
     * <hr>
     * 这个方法运行在setAdapter之前，且absListView一定不为空.
     */
    protected void initAbsListView(AbsListView absListView){
        //do nothing
    }
    
    /**
     * 得到FooterView
     * @param 
     */
    public View getFooterView(){
        return mFooterView;
    }
    
    /**
     * 得到HeaderView
     */
    public View getHeaderView(){
        return mHeaderView;
    }
    
    /**
     * 是否包含FooterView
     */
    public boolean containsHeaderView(){
        return mContainHeader;
    }
    
    /**
     * 是否包含HeaderView
     */
    public boolean containFooterView(){
        return mContainFooter;
    }
    
    /**
     * 如果不需要延迟加载，返回Null;
     */
    protected abstract View initFooterView(LayoutInflater inflater);
    
    /**
     * AbsListView的HeaderView，如果不需要HeaderView，返回null
     * <br>
     * 如果HeaderView不唯一，<strong>Override</strong> {@link #initAbsListView(AbsListView)},并在中添加HeaderView
     * @return null or headerView
     */
    protected abstract View initHeaderView(LayoutInflater inflater);
    protected View initTitleView(LayoutInflater inflater, ViewGroup root) {
    	return root;
    }
    
    @Override
    protected void dealloc() {
        this.mFooterView  = null;
        this.mHeaderView  = null;
        this.mAbsListView = null;
        this.mAncestor    = null;
        this.mContainHeader = false;
        this.mContainFooter = false;
        super.dealloc();
    }
    
    /**
     * 实现这个接口表示你的View可以添加FooterView
     * @author Chaos    
     * @date 2012-12-17
     */
    public static interface FooterViewCarriers{
        public void addFooterView(View ancestor,View footerView);
        public void removeFooterView(View ancestor,View footerView);
    }
    
    /**
     * 实现这个接口表示你的View可以添加HeaderView
     * @author Chaos    
     * @date 2012-12-17
     */
    public static interface HeaderViewCarriers{
        public void addHeaderView(View ancestor,View headerView);
        public void removeHeaderView(View ancestor,View headerView);
    }
}
